package com.example.a2205_fx.live;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.a2205_fx.R;
import com.example.a2205_fx.adapter.GiftAdapter;
import com.example.a2205_fx.adapter.MessageAdapter;
import com.example.a2205_fx.adapter.VideoAdapter;
import com.example.a2205_fx.adapter.VideoLiveAdapter;
import com.example.a2205_fx.base.BaseActivity;
import com.example.a2205_fx.database.Account;
import com.example.a2205_fx.database.AppDataBaseUtil;
import com.example.a2205_fx.databinding.ActivityLiveBinding;
import com.example.a2205_fx.entity.GiftEntity;
import com.example.a2205_fx.entity.MessageEntity;
import com.example.a2205_fx.entity.VideoEntity;
import com.example.a2205_fx.pay.PayActivity;
import com.kaisengao.likeview.like.KsgLikeView;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;

public class LiveActivity extends BaseActivity<ActivityLiveBinding,LiveViewModel> {
    List<VideoEntity.DataBean> videos = new ArrayList<>();
    VideoLiveAdapter videoLiveAdapter;

    List<GiftEntity.DataBean> gifts = new ArrayList<>();
    GiftAdapter giftAdapter;
    int page = 2;
    int size = 10;
    int index;

    Account account;

    List<MessageEntity> list = new ArrayList<>();
    MessageAdapter messageAdapter;

    private DanmakuContext danmakuContext;
    private BaseDanmakuParser parser = new BaseDanmakuParser() {
        @Override
        protected IDanmakus parse() {
            return new Danmakus();
        }
    };


    @Override
    protected void initData() {

        viewModel.success.observe(this, new Observer<VideoEntity>() {
            @Override
            public void onChanged(VideoEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    videos.addAll(entity.getData());
                    videoLiveAdapter.notifyDataSetChanged();
                    //展示指定下标的item
                    binding.rv.scrollToPosition(index);
                }
            }
        });
        viewModel.giftSuccess.observe(this, new Observer<GiftEntity>() {
            @Override
            public void onChanged(GiftEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    gifts.clear();
                    gifts.addAll(entity.getData());
                    giftAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    @Override
    protected void initView() {
        index = (int) getIntent().getExtras().get("index");
        videoLiveAdapter = new VideoLiveAdapter(R.layout.item_live,videos);
        binding.rv.setAdapter(videoLiveAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        binding.rv.setLayoutManager(linearLayoutManager);

        viewModel.video(page,size);

        //滑动分割
        PagerSnapHelper helper = new PagerSnapHelper();
        helper.attachToRecyclerView(binding.rv);
        //滑动自动播放
        binding.rv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int position = linearLayoutManager.findFirstVisibleItemPosition();
                index = position;
                StandardGSYVideoPlayer gsyVideoPlayer = (StandardGSYVideoPlayer) videoLiveAdapter.getViewByPosition(position,R.id.gsy);
                if(gsyVideoPlayer!=null){
                    gsyVideoPlayer.startPlayLogic();
                }
            }
        });
        //点击事件
        videoLiveAdapter.addChildClickViewIds(R.id.live_close,R.id.iv_xinhuan,R.id.iv_gift,
                R.id.gift_close,R.id.goMoney,R.id.tv_message,R.id.et_send);
        videoLiveAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()){
                    case R.id.live_close:
                        closeLive(position);
                        break;
                    case R.id.iv_xinhuan:
                        xinhuan(position);
                        break;
                    case R.id.iv_gift:
                        binding.rv.setFlag(false);
                        opengift(position);
                        break;
                    case R.id.gift_close:
                        binding.rv.setFlag(true);
                        closegift(position);
                        break;
                    case R.id.goMoney:
                        toPay();
                        break;
                    case R.id.tv_message:
                        openMessage(position);//打开输入框
                        break;
                    case R.id.et_send:
                        sendMessage(position);//发送弹幕聊天信息等
                        break;

                }
            }
        });

    }

    private void initMessage(int position) {
        messageAdapter = new MessageAdapter(R.layout.item_message,list);
        RecyclerView rvMessage = (RecyclerView) videoLiveAdapter.getViewByPosition(position, R.id.rv_message);
        rvMessage.setAdapter(messageAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);
        rvMessage.setLayoutManager(linearLayoutManager);

    }

    private void initDanmu(int position) {
        Log.d("sss", "initDanmu: "+index);
        danmakuContext  = DanmakuContext.create();
        DanmakuView danmakuView = (DanmakuView) videoLiveAdapter.getViewByPosition(position, R.id.danmu);
        Log.d("sss", "initDanmu: "+danmakuView);
        danmakuView.enableDanmakuDrawingCache(false);
        danmakuView.removeAllDanmakus(true);
        danmakuView.clear();
        danmakuView.prepare(parser,danmakuContext);
    }

    private void sendMessage(int position) {
        //获取输入框的内容
        EditText et = (EditText) videoLiveAdapter.getViewByPosition(position, R.id.et);
        String trim = et.getText().toString().trim();

        //实现发送弹幕
        DanmakuView danmakuView = (DanmakuView) videoLiveAdapter.getViewByPosition(position, R.id.danmu);
        danmakuView.enableDanmakuDrawingCache(false);
        danmakuView.removeAllDanmakus(true);
        danmakuView.clear();

        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        danmaku.text = trim;
        danmaku.textColor = Color.RED;
        danmaku.borderColor = Color.GREEN;
        danmaku.textSize = 80;
        danmakuView.addDanmaku(danmaku);
        danmakuView.start();

        MessageEntity entity = new MessageEntity(SPUtils.getInstance().getString("username"), trim);
        list.add(entity);
        messageAdapter.notifyDataSetChanged();
        //滑动到最后一行
        RecyclerView rvMessage = (RecyclerView) videoLiveAdapter.getViewByPosition(position, R.id.rv_message);
        rvMessage.scrollToPosition(list.size()-1);

        et.setText("");

        ConstraintLayout clEt = (ConstraintLayout) videoLiveAdapter.getViewByPosition(position, R.id.cl_et);
        clEt.setVisibility(View.GONE);

    }

    private void openMessage(int position) {
        ConstraintLayout clEt = (ConstraintLayout) videoLiveAdapter.getViewByPosition(position, R.id.cl_et);
        clEt.setVisibility(View.VISIBLE);
        initMessage(position);
        initDanmu(position);
    }

    private void toPay() {
        Intent intent = new Intent(this, PayActivity.class);
        startActivityForResult(intent,201);
    }

    private void initMoney(int position) {
        //查询账户是否存在，不存在新建，存在显示金额
        String username = SPUtils.getInstance().getString("username");
        account = AppDataBaseUtil.getInstance().getAccountDao().queryBy(username);
        if(account==null){
            account = new Account(username,0);
            AppDataBaseUtil.getInstance().getAccountDao().insertA(account);
        }
        TextView tvMoney = (TextView) videoLiveAdapter.getViewByPosition(position, R.id.tv_money);
        tvMoney.setText(account.getMoney()+"元");

    }

    private void closegift(int position) {
        ConstraintLayout clGift = (ConstraintLayout) videoLiveAdapter.getViewByPosition(position, R.id.cl_gift);
        clGift.setVisibility(View.GONE);
    }

    private void opengift(int position) {
        //显示礼物框
        ConstraintLayout clGift = (ConstraintLayout) videoLiveAdapter.getViewByPosition(position, R.id.cl_gift);
        clGift.setVisibility(View.VISIBLE);
        //初始化金额
        initMoney(position);
        //请求礼物数据
        //找到礼物rv
        RecyclerView rvGift = (RecyclerView) videoLiveAdapter.getViewByPosition(position, R.id.rv_gift);
        giftAdapter = new GiftAdapter(R.layout.item_gift,gifts);
        rvGift.setAdapter(giftAdapter);
        rvGift.setLayoutManager(new GridLayoutManager(this,3));
        viewModel.gift();

        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                //选中了就发送
                sendGift(position);
            }
        });

    }

    private void sendGift(int position) {
        if(account.getMoney()<gifts.get(position).getPrice()){
            ToastUtils.showLong("余额不足，请充值");
            return;
        }
        account.setMoney(account.getMoney()-gifts.get(position).getPrice());
        AppDataBaseUtil.getInstance().getAccountDao().updateA(account);
        TextView tvMoney = (TextView) videoLiveAdapter.getViewByPosition(index, R.id.tv_money);
        tvMoney.setText(account.getMoney()+"元");
        ImageView iv = (ImageView) videoLiveAdapter.getViewByPosition(index, R.id.animtor_gift);
        Glide.with(this).load(gifts.get(position).getGiftpath()).into(iv);
        iv.setVisibility(View.VISIBLE);
        int width = getWindowManager().getDefaultDisplay().getWidth();
        ObjectAnimator animator = ObjectAnimator.ofFloat(iv, "translationX", 0, width).setDuration(2000);
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                iv.setVisibility(View.GONE);
            }
        });

    }

    private void xinhuan(int position) {
        KsgLikeView ksg = (KsgLikeView) videoLiveAdapter.getViewByPosition(position, R.id.ksg);
        ksg.addLikeImages(R.drawable.ic_xihuanred,R.drawable.ic_gift);
        ksg.addFavor();
    }

    private void closeLive(int position) {
        finish();
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_live;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==201&&resultCode==202){
            initMoney(index);
        }
    }
}